package handlers

import (
	"html/template"
	"log"
	"net/http"
	"sort"
	"time"

	"ai-collections/pkg/models"

	"github.com/gin-gonic/gin"
)

var noticeService *models.NoticeService

// NoticeData 是传递给模板的数据
type NoticeData struct {
	UserInfo      models.DownstreamUserInfo
	Notices       []models.Notice
	CurrentNotice *models.Notice
	IsOwner       bool
	Error         string
}

// SetNoticeService 设置公告服务
func SetNoticeService(service *models.NoticeService) {
	noticeService = service
}

// 获取用户信息
func getUserInfo(c *gin.Context) (*models.DownstreamUserInfo, error) {
	encryptedHeader := c.GetHeader("X-User-Info")
	if encryptedHeader != "" {
		userInfo, err := models.DecryptUserInfo(encryptedHeader, encryptionKey)
		if err != nil {
			log.Printf("Error decrypting user info: %v", err)
			return models.GuestUserInfo(), nil
		}
		return userInfo, nil
	}
	return models.GuestUserInfo(), nil
}

// NoticeListHandler 处理公告列表页面
func NoticeListHandler(c *gin.Context) {
	userInfo, _ := getUserInfo(c)

	notices, err := noticeService.GetAllNotices()
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	// 按发布时间降序排序，最新的公告显示在前面
	sort.Slice(notices, func(i, j int) bool {
		return notices[i].CreatedAt.After(notices[j].CreatedAt)
	})

	data := NoticeData{
		UserInfo: *userInfo,
		Notices:  notices,
		IsOwner:  userInfo.IsOwner,
	}

	tmplPath := GetTemplatePath("notice_list.html")
	tmpl, err := template.ParseFiles(tmplPath)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	if err := tmpl.Execute(c.Writer, data); err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
	}
}

// NoticeDetailHandler 处理公告详情页面
func NoticeDetailHandler(c *gin.Context) {
	id := c.Param("id")
	userInfo, _ := getUserInfo(c)

	notice, err := noticeService.GetNoticeByID(id)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	if notice == nil {
		c.Redirect(http.StatusFound, "/ai-collections/notice")
		return
	}

	data := NoticeData{
		UserInfo:      *userInfo,
		CurrentNotice: notice,
		IsOwner:       userInfo.IsOwner,
	}

	tmplPath := GetTemplatePath("notice_detail.html")
	tmpl, err := template.ParseFiles(tmplPath)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	if err := tmpl.Execute(c.Writer, data); err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
	}
}

// NoticeEditHandler 处理公告编辑页面
func NoticeEditHandler(c *gin.Context) {
	id := c.Param("id")
	userInfo, _ := getUserInfo(c)

	// 检查权限
	if !userInfo.IsOwner {
		c.Redirect(http.StatusFound, "/ai-collections/notice")
		return
	}

	notice, err := noticeService.GetNoticeByID(id)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	if notice == nil {
		c.Redirect(http.StatusFound, "/ai-collections/notice")
		return
	}

	data := NoticeData{
		UserInfo:      *userInfo,
		CurrentNotice: notice,
		IsOwner:       userInfo.IsOwner,
	}

	tmplPath := GetTemplatePath("notice_edit.html")
	tmpl, err := template.ParseFiles(tmplPath)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	if err := tmpl.Execute(c.Writer, data); err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
	}
}

// NoticeNewHandler 处理新建公告页面
func NoticeNewHandler(c *gin.Context) {
	userInfo, _ := getUserInfo(c)

	// 检查权限
	if !userInfo.IsOwner {
		c.Redirect(http.StatusFound, "/ai-collections/notice")
		return
	}

	data := NoticeData{
		UserInfo: *userInfo,
		IsOwner:  userInfo.IsOwner,
	}

	tmplPath := GetTemplatePath("notice_edit.html")
	tmpl, err := template.ParseFiles(tmplPath)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	if err := tmpl.Execute(c.Writer, data); err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
	}
}

// NoticeSaveHandler 处理保存公告
func NoticeSaveHandler(c *gin.Context) {
	userInfo, _ := getUserInfo(c)

	// 检查权限
	if !userInfo.IsOwner {
		c.JSON(http.StatusForbidden, gin.H{"error": "无权限执行此操作"})
		return
	}

	var notice models.Notice
	if err := c.ShouldBind(&notice); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请求数据无效"})
		return
	}

	// 设置作者和更新时间
	notice.Author = userInfo.Username
	notice.UpdatedAt = time.Now()

	// 如果是编辑现有公告，获取原有公告以保留创建时间
	if notice.ID != "" {
		existingNotice, err := noticeService.GetNoticeByID(notice.ID)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "获取原有公告失败"})
			return
		}
		if existingNotice != nil {
			notice.CreatedAt = existingNotice.CreatedAt
		}
	}

	if err := noticeService.SaveNotice(notice); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "保存公告失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"success": true, "id": notice.ID})
}

// NoticeDeleteHandler 处理删除公告
func NoticeDeleteHandler(c *gin.Context) {
	id := c.Param("id")
	userInfo, _ := getUserInfo(c)

	// 检查权限
	if !userInfo.IsOwner {
		c.JSON(http.StatusForbidden, gin.H{"error": "无权限执行此操作"})
		return
	}

	if err := noticeService.DeleteNotice(id); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "删除公告失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"success": true})
}
